/**
 * Created by 何晓波 on 2022/5/12.
 * Edit by 何晓波 on
 * 当文字超出容器，文字自动滚动
 */

/**
 * 生成唯一的名称
 * */
function generateUniqueString() {
  return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
}
// 滚动时长（s）
const textHorizontalMarquee = {
  inserted(el, binding) {
    console.log("textHorizontalMarquee")
    const { during = 8 } = binding.value || {}
    const wrapper = document.createElement('div')
    const content = document.createElement('div')

    // 把原始内容移到新的 wrapper 内
    content.innerHTML = el.innerHTML
    wrapper.appendChild(content)
    el.innerHTML = ''
    el.appendChild(wrapper)

    // 初始化样式
    Object.assign(el.style, {
      overflow: 'hidden',
      position: 'relative'
    })
    Object.assign(wrapper.style, {
      display: 'inline-block',
      whiteSpace: 'nowrap',
      position: 'absolute',
      left: 0,
      top: 0
    })

    const startMarquee = ()=>{
      const contentWidth = content.scrollWidth
      const containerWidth = el.clientWidth

      // 如果内容超出容器宽度，启动动画
      if (contentWidth > containerWidth) {
        const scrollLength = contentWidth - containerWidth
        const id = generateUniqueString()
        const ruleName = `text-marquee-${id}`
        wrapper.style.animation = `${ruleName} ${during}s linear infinite`
        // 获取样式表并插入 keyframes 动画
        const styleSheet = document.styleSheets[0]
        const rule = `
          @keyframes text-marquee-${id} {
            0% { transform: translateX(0); }
            40%, 50% { transform: translateX(${-scrollLength}px); }
            90% { transform: translateX(0); }
          }
        `
        // 插入样式
        styleSheet.insertRule(rule, styleSheet.cssRules.length)

        // 绑定到元素上，用于在解绑时清理
        el._marqueeRuleName = ruleName
      }
    }
    // 使用 requestAnimationFrame 确保渲染完成后计算
    requestAnimationFrame(startMarquee)
  },

  // 清理动画样式
  unbind(el) {
    const styleSheet = document.styleSheets[0]
    const ruleName = el._marqueeRuleName
    const _ruleIndex = Array.from(styleSheet.cssRules).findIndex(
      (rule)=>rule.name && rule.name === ruleName
    )
    // 如果存在有效的规则索引，则删除该规则
    if (_ruleIndex !== undefined && _ruleIndex >= 0) {
      styleSheet.deleteRule(_ruleIndex)
    }
  }
}

export default textHorizontalMarquee
